import {
  getUserProfileInfo,
  modifyUserInfo
} from '../../../api/user.js';
import {
  setStorageItem
} from '../../../utils/storage.js';
import { validateCheckResult } from '../../../utils/index.js';
import {
  initQiniu,
  uploadFile
} from '../../../api/qiniu/upload.js';
import {
  reqSecurityMsgCheck
} from '../../../api/system.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {
      user_avator: '',
      province: '',
      city: '',
      userName: ''
    },
    defaultAvator: 'https://ustatic.hudongmiao.com/emcee/common/b51d744c7b3f4f379d3f7f989c295daf', //默认头像
    isShowNameDialog: false, // 修改用户名称的弹窗
    newName: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取用户数据
    this.getUserInfo();
    // 初始化七牛
    initQiniu();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  // 修改头像
  changeAvator() {
    wx.showActionSheet({
      itemList: ['拍摄', '从相册中选择'],
      success: (res) => {
        const {
          tapIndex
        } = res;
        //拍摄
        if (Number(tapIndex) === 0) {
          wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            sizeType: ['compressed'],
            camera: 'front',
            success: async (res) => {
              const url = res.tempFiles[0].tempFilePath;
              // 将头像上传至七牛云
              const uploadRes = await uploadFile([url]);
              const targetUrl = uploadRes[0].imageURL;
              console.log('上传后的地址', targetUrl);
              // 调用修改接口
              this.modifyUserInfo({
                avator: targetUrl
              });
              // 更改本地存储数据
              setStorageItem('headerImgPath', targetUrl)
              this.setData({
                ['user.user_avator']: url
              })
            }
          })
        }
        //相册
        if (Number(tapIndex) === 1) {
          wx.chooseMedia({
            mediaType: ['image'],
            sourceType: ['album'],
            sizeType: ['compressed'],
            count: 1,
            success: async (res) => {
              const url = res.tempFiles[0].tempFilePath;
              // 将头像上传至七牛云
              const uploadRes = await uploadFile([url]);
              const targetUrl = uploadRes[0].imageURL;
              console.log('上传后的地址', targetUrl);
              // 调用修改接口
              this.modifyUserInfo({
                avator: targetUrl
              });
              // 更改本地存储数据
              setStorageItem('headerImgPath', targetUrl)
              this.setData({
                ['user.user_avator']: url
              })
            }
          })
        }
      }
    })
  },
  // 修改用户名弹窗
  showChangeName() {
    this.setData({
      'isShowNameDialog': true
    })
  },
  // 关闭弹窗
  closeDialog() {
    this.setData({
      'isShowNameDialog': false,
      'newName': ''
    })
  },
  // 修改用户名
  async changeUserName() {
    if (this.data.newName.length === 0) {
      wx.showToast({
        icon: 'none',
        title: '用户名称不能为空',
      });
      return;
    }
 
    try {
      const checkRes = await reqSecurityMsgCheck(this.data.newName);
      if(!validateCheckResult(checkRes.data.data?.msg_sec_check)) {
        throw new Error('内容非法');
      }
      // 调用修改接口
      this.modifyUserInfo({
        emcee_name: this.data.newName
      })
      //修改本地用户名称
      this.setData({
        'user.userName': this.data.newName
      })
      setStorageItem('user_name', this.data.newName);
      //关闭窗口
      this.setData({
        'isShowNameDialog': false,
        'newName': ''
      })
    } catch (err) {
      console.log(err);
      wx.showToast({
        title: '名称非法!',
        icon: 'error'
      });
    }
  },
  // 修改所属地区
  changeArea(e) {
    console.log(e);
    const values = e.detail.value;
    const province = values[0];
    const city = values[1];
    // 调用修改接口
    this.modifyUserInfo({
      province: province,
      city: city
    })
    this.setData({
      'user.province': province,
      'user.city': city
    })
  },
  // 退出登录的逻辑
  logout() {
    // 弹出提示
    wx.showModal({
      content: '确定退出登录？',
      confirmText: '确定',
      confirmColor: '#007AFF',
      cancelText: '取消',
      cancelColor: '#007AFF',
      complete: (res) => {
        if (res.confirm) {
          wx.clearStorageSync();
          //路由回到首页
          wx.reLaunch({
            url: '/pages/index/index',
          })
        }
      }
    })
  },
  // 获取用户数据
  async getUserInfo() {
    const {
      data: userInfo
    } = await getUserProfileInfo();
    const {
      province,
      avator,
      city,
      emcee_name //用户名
    } = userInfo;
    this.setData({
      'user.user_avator': avator,
      'user.userName': emcee_name,
      'user.province': province,
      'user.city': city
    });
  },
  // 修改用户信息
  /**
   * 
   * @param {*} paramObj  
   * paramObj: {
   *    avator,       //用户头像
   *    emcee_name,   //用户昵称
   *    province,   //省
   *    city  //市
   * }
   */
  async modifyUserInfo(paramObj) {
    const {
      data: res
    } = await modifyUserInfo(paramObj);
    console.log('修改结果', res);
  }
})